package com.example.demo.controller;

import com.example.demo.model.WebLink;
import com.example.demo.model.LinkCategory;
import com.example.demo.service.WebLinkService;
import com.example.demo.service.UserService;
import com.example.demo.service.LinkCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/dashboard/weblinks")
public class WebLinkController {
    
    private final WebLinkService webLinkService;
    private final UserService userService;
    private final LinkCategoryService linkCategoryService;
    
    @Autowired
    public WebLinkController(WebLinkService webLinkService, UserService userService, LinkCategoryService linkCategoryService) {
        this.webLinkService = webLinkService;
        this.userService = userService;
        this.linkCategoryService = linkCategoryService;
    }
    
    @GetMapping
    public String listWebLinks(Model model) {
        try {
            List<WebLink> webLinks = webLinkService.getAllWebLinks();
            model.addAttribute("webLinks", webLinks);
            model.addAttribute("webLink", new WebLink());
            model.addAttribute("user", userService.getCurrentUser());
            return "dashboard/weblinks/list";
        } catch (Exception e) {
            model.addAttribute("errorMessage", "获取网站链接列表失败: " + e.getMessage());
            model.addAttribute("webLinks", null);
            model.addAttribute("webLink", new WebLink());
            model.addAttribute("user", userService.getCurrentUser());
            return "dashboard/weblinks/list";
        }
    }
    
    @GetMapping("/new")
    public String newWebLinkForm(Model model) {
        model.addAttribute("webLink", new WebLink());
        model.addAttribute("user", userService.getCurrentUser());
        model.addAttribute("categories", linkCategoryService.findAllLinkCategories());
        return "dashboard/weblinks/form";
    }
    
    @PostMapping
    public String saveWebLink(@ModelAttribute WebLink webLink, 
                             @RequestParam(value = "categoryId", required = false) Long categoryId, 
                             RedirectAttributes redirectAttributes) {
        try {
            if (categoryId != null) {
                Optional<LinkCategory> category = linkCategoryService.findById(categoryId);
                category.ifPresent(webLink::setCategory);
            } else {
                webLink.setCategory(null);
            }
            
            webLinkService.saveWebLink(webLink);
            redirectAttributes.addFlashAttribute("successMessage", 
                webLink.getId() == null ? "网站链接创建成功!" : "网站链接更新成功!");
            return "redirect:/dashboard/weblinks";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "保存网站链接失败: " + e.getMessage());
            return "redirect:/dashboard/weblinks";
        }
    }
    
    @GetMapping("/edit/{id}")
    public String editWebLinkForm(@PathVariable Long id, Model model, RedirectAttributes redirectAttributes) {
        try {
            Optional<WebLink> webLinkOpt = webLinkService.getWebLinkById(id);
            if (webLinkOpt.isPresent()) {
                model.addAttribute("webLink", webLinkOpt.get());
                model.addAttribute("user", userService.getCurrentUser());
                model.addAttribute("categories", linkCategoryService.findAllLinkCategories());
                return "dashboard/weblinks/form";
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "未找到ID为 " + id + " 的网站链接");
                return "redirect:/dashboard/weblinks";
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "编辑网站链接失败: " + e.getMessage());
            return "redirect:/dashboard/weblinks";
        }
    }
    
    @GetMapping("/delete/{id}")
    public String deleteWebLink(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            webLinkService.deleteWebLink(id);
            redirectAttributes.addFlashAttribute("successMessage", "网站链接删除成功!");
            return "redirect:/dashboard/weblinks";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除网站链接失败: " + e.getMessage());
            return "redirect:/dashboard/weblinks";
        }
    }
    
    @GetMapping("/search")
    public String searchWebLinks(@RequestParam(required = false) String title,
                               @RequestParam(required = false) String url,
                               Model model) {
        try {
            List<WebLink> webLinks;
            if (title != null && !title.isEmpty()) {
                webLinks = webLinkService.searchWebLinksByTitle(title);
                model.addAttribute("searchTerm", "标题包含: " + title);
            } else if (url != null && !url.isEmpty()) {
                webLinks = webLinkService.searchWebLinksByUrl(url);
                model.addAttribute("searchTerm", "URL包含: " + url);
            } else {
                webLinks = webLinkService.getAllWebLinks();
            }
            
            model.addAttribute("webLinks", webLinks);
            model.addAttribute("webLink", new WebLink());
            model.addAttribute("user", userService.getCurrentUser());
            return "dashboard/weblinks/list";
        } catch (Exception e) {
            model.addAttribute("errorMessage", "搜索网站链接失败: " + e.getMessage());
            model.addAttribute("webLinks", null);
            model.addAttribute("webLink", new WebLink());
            model.addAttribute("user", userService.getCurrentUser());
            return "dashboard/weblinks/list";
        }
    }
    
    @GetMapping("/toggle/{id}")
    public String toggleActive(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            webLinkService.toggleActive(id);
            redirectAttributes.addFlashAttribute("successMessage", "网站链接状态已更新!");
            return "redirect:/dashboard/weblinks";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "更新网站链接状态失败: " + e.getMessage());
            return "redirect:/dashboard/weblinks";
        }
    }
    
    @PostMapping("/order/{id}")
    public String updateOrder(@PathVariable Long id, @RequestParam Integer order, RedirectAttributes redirectAttributes) {
        try {
            webLinkService.updateDisplayOrder(id, order);
            redirectAttributes.addFlashAttribute("successMessage", "网站链接顺序已更新!");
            return "redirect:/dashboard/weblinks";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "更新网站链接顺序失败: " + e.getMessage());
            return "redirect:/dashboard/weblinks";
        }
    }
} 